import React, { createContext, useState } from 'react';
import classNames from 'classnames';
import { MenuItemBaseProps } from './menuItem';

type modeType = 'vertical' | 'horizontal';

export interface MenuBaseProps {
  /** 模式：垂直、水平 */
  mode?: modeType;
  /** 默认选中的下标 */
  defaultIndex?: number;
  /** 样式名称 */
  className?: string;
  style?: React.CSSProperties;
  children?: React.ReactNode;
  /** 点击选中触发的回调 */
  onSelected?: (key: number) => void;
  /**设置子菜单的默认打开 只在纵向模式下生效 */
  defaultOpenSubMenus?: string[];
}

export interface contextPorps {
  /** 点击选中的下标 */
  index: number;
  /** menu的格式 */
  mode?: modeType;
  /** 选中的回调 */
  selectedFn?: (index: number) => void;
  defaultOpenSubMenus?: string[];
}
export const MenuContext = createContext<contextPorps>({ index: 0 });

const Menu: React.FC<MenuBaseProps> = (props) => {
  const {
    children,
    className,
    style,
    defaultIndex,
    mode,
    onSelected,
    defaultOpenSubMenus,
  } = props;
  const [currentIndx, setCurrentIndx] = useState(defaultIndex);

  const classes = classNames('mid-menu', className, {
    [`mid-menu-${mode}`]: mode,
  });

  const handleClick = (index: number) => {
    setCurrentIndx(index);
    onSelected && onSelected(index);
  };

  const contextValue = {
    index: currentIndx ? currentIndx : 0,
    mode,
    selectedFn: handleClick,
    defaultOpenSubMenus,
  };

  const renderChild = () => {
    return React.Children.map(children, (child, index) => {
      const childComponent = child as React.FunctionComponentElement<
        MenuItemBaseProps
      >;
      // 判断用户传入的children是否为MenuItem或者SubMenu
      if (
        childComponent.type.name === 'MenuItem' ||
        childComponent.type.name === 'SubMenu'
      ) {
        // 给每个MenuItem一个默认的Index属性
        return React.cloneElement(childComponent, { index });
      } else
        console.error(
          'Warning: Menu has a child which is not a MenuItem or SubMenu',
        );
    });
  };

  return (
    <ul className={classes} style={style}>
      <MenuContext.Provider value={contextValue}>
        {renderChild()}
      </MenuContext.Provider>
    </ul>
  );
};

Menu.defaultProps = {
  defaultIndex: 0,
  mode: 'horizontal',
  defaultOpenSubMenus: [],
};

export default Menu;
